/**

*/
<template>
    <div>
        <div ref="map" id="map"></div>
        <!--  <div class="btns">
              <button @click="showStyle('circle')">显示样式circle</button>
              <button @click="showStyle('icon')">显示样式icon</button>

              <button @click="addMarkers">添加自定义图标</button>
          </div>-->
    </div>
</template>

<script>
    import "ol/ol.css";
    import {Map, View, Feature} from "ol";
    import {Tile as TileLayer, Vector as VectorLayer} from "ol/layer"
    import {XYZ, Vector as VectorSource} from "ol/source"
    import {fromLonLat} from "ol/proj"
    import {Circle, Point, LineString} from "ol/geom"
    import {Style, Fill, Text, Stroke} from "ol/style"
    import {getDistance} from "ol/sphere"


    export default {
        name: "AppCircleLink",
        data() {
            return {
                map: null,
                sites: [{
                    site: [116.400819, 39.916263],
                    name: '覆盖物1',
                }, {
                    site: [116.450819, 39.917263],
                    name: '覆盖物2',
                }, {
                    site: [116.350819, 39.857263],
                    name: '覆盖物3',
                }],
            }
        },
        mounted() {
            // 创建地图
            this.initMap();
        },
        methods: {
            /**
             * 初始化一个 openlayers 地图
             */
            initMap() {
                this.map = new Map({
                    target: "map",
                    view: new View({
                        center: fromLonLat([116.403218, 39.92372]),
                        zoom: 13,
                        constrainResolution: true,//设置缩放级别为整数
                        smoothResolutionConstraint: false,//关闭无级缩放地图
                    }),
                });

                var gaodeLayer = new TileLayer({
                    source: new XYZ({
                        url: "http://webrd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}"
                    })
                });
                this.map.addLayer(gaodeLayer);

                this.addPoint();//加载圆形
                this.addLabel();//添加标识
                this.addLink();
            },

            //绘制圆形
            addPoint() {
                let features = [];
                this.sites.forEach((item, index) => {
                    let feature = new Feature({
                        title: item.name + '  ' + index,
                        geometry: new Circle(fromLonLat(item.site), this.getRadius(2000)),
                    });

                    feature.setStyle(
                        new Style({
                            fill: new Fill({
                                color: 'rgba(32,157,230,1)'
                            })
                        })
                    );
                    features.push(feature);
                });

                let source = new VectorSource();
                source.addFeatures(features);
                let layer = new VectorLayer({
                    opacity: 0.2
                });
                layer.setSource(source);
                this.map.addLayer(layer);
            },

            getRadius(radius) {
                let metersPerUnit = this.map.getView().getProjection().getMetersPerUnit();
                let circleRadius = radius / metersPerUnit;
                return circleRadius;
            },

            addLabel() {
                let features = [];
                this.sites.forEach((item, index) => {
                    let feature = new Feature({
                        title: item.name + '  ' + index,
                        geometry: new Point(fromLonLat(item.site)),
                    });

                    feature.setStyle(
                        new Style({
                            text: new Text({
                                textAlign: 'center',
                                textBaseline: 'middle',
                                font: 'normal 17px 微软雅黑',
                                text: item.name,
                                fill: new Fill({color: 'red'}),
                            })
                        })
                    );
                    features.push(feature);
                });

                let source = new VectorSource();
                source.addFeatures(features);
                let layer = new VectorLayer({
                    opacity: 1
                });
                layer.setSource(source);
                this.map.addLayer(layer);
            },

            addLink() {
                this.sites.push(this.sites[0]);//注意这里，只有这样才能把所有点相连，相当于是第四个点（结尾点）
                let linkData = [];
                this.sites.forEach(item => {
                    linkData.push(fromLonLat(item.site));
                });

                let features = [];
                let featureLine = new Feature({
                    geometry: new LineString(linkData)
                });
                let lineStyle = new Style({
                    stroke: new Stroke({
                        color: '#000',
                        lineDash: [10, 10, 10, 10],//关键点
                        width: 2,
                    })
                });
                featureLine.setStyle(lineStyle);
                features.push(featureLine);

                let distanceList = [];
                for (let index = 0; index < this.sites.length - 1; index++) {
                    let x = (this.sites[index].site[0] + this.sites[index + 1].site[0]) / 2;
                    let y = (this.sites[index].site[1] + this.sites[index + 1].site[1]) / 2;
                    let site = fromLonLat([x, y]);//距离展示位置在线段中心点位置
                    let length = getDistance(this.sites[index].site, this.sites[index + 1].site)
                    distanceList.push({
                        site,
                        length,
                    });
                }
                console.log('距离数组：', distanceList)
                distanceList.forEach((item, index) => {
                    let feature = new Feature({
                        title: 'Line  ' + index,
                        geometry: new Point(item.site),//注意上面已经采用了函数fromLonLat
                    });

                    feature.setStyle(
                        new Style({
                            text: new Text({
                                textAlign: 'center',
                                textBaseline: 'middle',
                                font: 'normal 12px 微软雅黑',
                                text: item.length.toFixed(0) + 'm',
                                padding: [1, 1, 1, 1],
                                backgroundFill: new Fill({color: '#d5e2f9'}),
                                fill: new Fill({color: 'red'}),
                            })
                        })
                    );
                    features.push(feature);
                });

                console.log(features)
                let source = new VectorSource();
                source.addFeatures(features);
                let layer = new VectorLayer();
                layer.setSource(source);
                this.map.addLayer(layer);
            },
        }
    };

</script>

<style scoped>
    #map {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 10px;
        left: 10px;
    }

    /*移除OSM的链接*/
    :deep(.ol-attribution) {
        display: none;
    }

    /*
        .btns {
            position: fixed;
            top: 100px;
            left: 200px;
        }*/
</style>